<!--
 * @Descripttion: users用户
 * @version:
 * @Author: cxguo
 * @Date: 2019-08-17 20:26:23
 * @LastEditors: cxguo
 * @LastEditTime: 2020-07-07 16:19:48
 -->
<template>
  <div class="app-container">
    <div>
      <el-input
        v-model="searchData.keywords"
        style="width: 360px"
        placeholder="按昵称, 手机号,查询."
      >
        <el-button slot="append" icon="el-icon-search" type="primary" :loading="btnLoading.search" @click="btnSearch" />
      </el-input>
      <el-button class="fl" type="primary" @click="btnAddUsers">
        添 加
      </el-button>
    </div>
    <el-table
      ref="usersData"
      v-loading="tableLoading.users"
      :data="getTableData('users')"
      style="width: 100%"
      border
      @selection-change="onSelectionChange"
    >
      <el-table-column label="昵称" width="100" prop="username" align="left" />
      <el-table-column label="手机号" width="200" prop="phonenum" align="left" />
      <el-table-column label="创建时间" width="100" prop="createTime" align="left" />
      <el-table-column label="角色" width="100" prop="createTime" align="left">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="btnSetRole(scope.$index, scope.row)">设 置
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center" fixed="left">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="btnUpdate(scope.$index, scope.row)">编 辑
          </el-button>
          <el-button size="mini" type="danger" :loading="currentId === scope.$index" @click="btnDelete(scope.$index, scope.row)">删 除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes,prev, pager, next,jumper"
        :page-size="pageInfo.rows"
        :page-sizes="[20,30,40]"
        :current-page.sync="pageInfo.page"
        :total="pageInfo.total"
        @size-change="onSizeChange"
        @current-change="onCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import { oftenuse } from '@/libs/mixins'
import UserSave from './save'
import SelectRole from './select-role'
import { listSonData, delData, updateRoles } from '@/api/sys/users.js'

export default {
  name: 'Users',
  mixins: [oftenuse],
  props: {
  },
  data() {
    return {
      currentId: null
    }
  },
  computed: {
  },
  watch: {
  },
  created() {
    this.setTableData('users', [])
    this.listUserData()
  },
  methods: {
    btnSearch() {
      this.pageInfo.current = 1
      this.setBtnLoading('search', true)
      this.listUserData().then(() => {
        this.setBtnLoading('search', false)
      }).catch(err => {
        console.log(err)
        this.setBtnLoading('search', false)
      })
    },
    btnSetRole(index, row) {
      this.popRoleMsgBox(row.uid)
    },
    btnAddUsers() {
      this.popMsgBox()
    },
    btnUpdate(index, row) {
      this.popMsgBox(row)
    },
    btnDelete(index, row) {
      this.isAllowDel().then(res => {
        this.currentId = index
        this.delUserData([row.uid]).then(res => {
          this.listUserData()
          this.currentId = null
        })
      })
    },
    popRoleMsgBox(userId) {
      const h = this.$createElement
      const vNode = h(SelectRole, { props: { userId }})
      this.$msgbox({
        title: '用户角色管理',
        message: vNode,
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            const compInstance = instance.$slots.default[0].componentInstance
            const roleSelectData = compInstance.getTableSelectionData('role')
            if (roleSelectData) {
              const params = { sysUser: { uid: userId }, roleList: roleSelectData }
              this.updateUserRoles(params).then(res => {
                if (res.data.flag) {
                  done()
                  instance.$slots.default = null
                }
              })
            }
          } else {
            done()
            instance.$slots.default = null
          }
        }
      }).then(res => {
      })
    },
    popMsgBox(data) {
      const h = this.$createElement
      const vNode = h(UserSave, { props: { userData: data }})
      this.$msgbox({
        title: '子账号管理',
        message: vNode,
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            const compInstance = instance.$slots.default[0].componentInstance
            compInstance.handleValid('userData').then(() => {
              compInstance.saveData().then(res => {
                this.listUserData()
                instance.$slots.default = null
                done()
              })
            })
          } else {
            done()
          }
        }
      })
    },
    delUserData(userIdArray) {
      return delData(userIdArray).then(res => {
        if (res.data.flag) {
          return this.$notify.success({ title: '删除成功！' })
        } else {
          return this.$notify.error({ title: '删除失败！', message: res.data.message || '' })
        }
      }).catch(err => {
        return this.$notify.error({ title: '删除异常！', message: err || '' })
      })
    },
    updateUserRoles(params) {
      return new Promise((resolve, reject) => {
        updateRoles(params).then(res => {
          resolve(res)
          if (res.data.flag) {
            this.$notify.success({ title: '设置成功！' })
            this.listUserData()
          } else {
            this.$notify.error({ title: '设置失败！', message: res.data.message || '' })
          }
        }).catch(err => {
          reject(err)
          return this.$notify.error({ title: '设置异常！', message: err || '' })
        })
      })
    },
    listUserData(params = { data: this.searchData, pageInfo: this.pageInfo }) {
      return listSonData(params).then(res => {
        if (res.data.flag) {
          this.setTableData('users', res.data.data)
        }
      })
    },
    onCurrentChange() {},
    onSizeChange() {},
    onSelectionChange(selectData) {
      this.setTableSelectionData('users', selectData)
    }
  }
}
</script>

<style scoped>
</style>
